package com.example.mylearn.juc.example.learn.once;


import java.util.concurrent.Semaphore;

/**
 * Semaphore  记住，数字是允许访问当前资源的线程
 */
public class day1Semaphore {


    private static Semaphore a = new Semaphore(1);
    private static Semaphore b = new Semaphore(0);
    private static Semaphore c = new Semaphore(0);


    static class SemaphoreA extends Thread {

        @Override
        public void run() {
            try {
                for (int i = 0; i < 10; i++) {
                    a.acquire();
                    System.out.print("A");
                    b.release();
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }

    static class SemaphoreB extends Thread {

        @Override
        public void run() {
            try {
                for (int i = 0; i < 10; i++) {
                    b.acquire();
                    System.out.print("B");
                    c.release();
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }

    static class SemaphoreC extends Thread {

        @Override
        public void run() {
            try {
                for (int i = 0; i < 10; i++) {
                    c.acquire();
                    System.out.print("C");
                    a.release();
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }


    public static void main(String[] args) {
        new SemaphoreA().start();
        new SemaphoreB().start();
        new SemaphoreC().start();
    }










}
